/*
 * Created on Feb 25, 2005
 */
package com.scalar.chiptrack.finance.openpo.actioncommands;

import com.scalar.chiptrack.ChipTrackExtendedAction;
import com.scalar.chiptrack.users.ErrorReport;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.finance.openpo.forms.PurchaseOrderReceiptForm;
import com.scalar.chiptrack.finance.openpo.PurchaseOrderLineItemLotDataEntry;
import com.scalar.chiptrack.finance.openpo.PurchaseOrderLineItemLotDataEntryList;
import com.scalar.chiptrack.finance.openpo.ReceivingLineItem;
import com.scalar.chiptrack.finance.openpo.ReceivingLineItemList;
import com.scalar.chiptrack.finance.openpo.dao.PurchaseOrderDAO;

import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Iterator;

/**
 * @author Ravikanth
**/
public class ReceivingLineItemLotDataEntryCommand extends ChipTrackExtendedAction
{
	public ActionForward executeRequest( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
	{
		HashMap errors              = ( HashMap ) request.getAttribute( ERROR_MESSAGES );
		HashMap info                = ( HashMap ) request.getAttribute( INFO_MESSAGES );
		String actionForward 		= "recevingLineItemLotEntry";
		HttpSession mSession 		= request.getSession();
		PurchaseOrderReceiptForm receiptForm = ( PurchaseOrderReceiptForm ) form;
		ReceivingLineItem recevingLineItem;
		ReceivingLineItemList receivingLineItemList;
		PurchaseOrderLineItemLotDataEntryList purchaseOrderLineItemLotDataEntryList;

		int recevingLineItemNumber = -1;
		Iterator lineItemIterator;
		
		try
		{
            request.setAttribute( "processNameList", PurchaseOrderDAO.loadProcessNames( receiptForm.getVendor_id() ) );
            if ( request.getParameter( "openRecevingLineItemLotEntry" ) != null )
            {
                if ( receiptForm.getOpenPOLotList() == null || receiptForm.getOpenPOLotList().isEmpty() )
                {
                    purchaseOrderLineItemLotDataEntryList = PurchaseOrderDAO.loadLotsForReceipts( null, receiptForm.getPurchaseOrderNumber(), 0, receiptForm.getVendor_id(), 0, receiptForm.getReceipt_id() );
                    
                    // Remove all the parts that are already recevied from the same purchase order receipt.
                    removeExistingProcessStepIds( purchaseOrderLineItemLotDataEntryList, receiptForm.getReceivingLineItemList() );
                    
                    receiptForm.setOpenPOLotList( purchaseOrderLineItemLotDataEntryList );
                }
                actionForward = "openRecevingLineItemLotEntry";
            }
            else
            {
                recevingLineItemNumber = Integer.parseInt( request.getParameter( "purchaseOrderLineItemNumber" ) );
                receivingLineItemList = receiptForm.getReceivingLineItemList();
                lineItemIterator = receivingLineItemList.iterator();

                //for assigning New Purchase Order Line Item Data Entry to the selected Purchase Order Line Item, if it's is empty.
                while ( lineItemIterator.hasNext() )
                {
                    recevingLineItem = ( ReceivingLineItem ) lineItemIterator.next();
                    // If Selected Line item index and Line Item Index match then set values of Purchasing Lot Number List.
                    if ( recevingLineItem.getPurchaseOrderLineItemNumber() == recevingLineItemNumber )
                    {
                        if ( recevingLineItem.getPurchaseOrderLineItemLotDataEntryList() == null || recevingLineItem.getPurchaseOrderLineItemLotDataEntryList().size() == 0 )
                        {
                        	purchaseOrderLineItemLotDataEntryList = PurchaseOrderDAO.loadLotsForReceipts( null, receiptForm.getPurchaseOrderNumber(), recevingLineItem.getProcessStepId(), receiptForm.getVendor_id(), recevingLineItem.getRecevingLineItem_Id(), receiptForm.getReceipt_id() );
                            recevingLineItem.setPurchaseOrderLineItemLotDataEntryList( purchaseOrderLineItemLotDataEntryList );
                        }
                        else
                        {
                        	purchaseOrderLineItemLotDataEntryList = PurchaseOrderDAO.loadLotsForReceipts( null, receiptForm.getPurchaseOrderNumber(), recevingLineItem.getProcessStepId(), receiptForm.getVendor_id(), recevingLineItem.getRecevingLineItem_Id(), receiptForm.getReceipt_id() );
                        	
                        	// By default line item will hold only the lots that are selected for the line item when purchase order is loaded.
                        	// If the user opens the po receipt again for modification and if he clicks on the lot pull screen system will only show
                        	// lots that are pulled, system will not show the additinal lots for pulling extra lots for the same receving lineitem.
                        	// We are checking for list size again because, if the user selects the lots and save lot information screen, and if he
                        	// opens the lot pull screen again, system is loading the lot information from DB again so the selection is being lost.
                        	if( purchaseOrderLineItemLotDataEntryList != null &&  purchaseOrderLineItemLotDataEntryList.size() > 0 )
                        	{
                        		if( purchaseOrderLineItemLotDataEntryList.size() > recevingLineItem.getPurchaseOrderLineItemLotDataEntryList().size() )
                        		{
                        			recevingLineItem.setPurchaseOrderLineItemLotDataEntryList( purchaseOrderLineItemLotDataEntryList );		
                        		}
                        		// It will fetch from session itself
                        	}
                        }
                        break;
                    }
                }

                actionForward = "recevingLineItemLotEntry";
            }
        }
		catch ( Exception e )
		{
			Logger.error( ERRROR_LOADING_PURCHASE_ORDER_LINE_ITEM_PURCHASING_LOT_DATA_ENTRY, e );
			errors.put( ERROR_INTERNAL_SERVER_ERROR, ERRROR_LOADING_PURCHASE_ORDER_LINE_ITEM_PURCHASING_LOT_DATA_ENTRY );
			mSession.setAttribute( ERROR_REPORT_OBJECT, new ErrorReport( ERRROR_LOADING_PURCHASE_ORDER_LINE_ITEM_PURCHASING_LOT_DATA_ENTRY, e ) );
			actionForward = "recevingLineItemLotEntry";
		}

		request.setAttribute( ERROR_MESSAGES, errors );
		request.setAttribute( INFO_MESSAGES, info );
		return mapping.findForward( actionForward );
	}

    /**
	 * @param processStepLotList
	 */
	private void printProcessStepLotList(PurchaseOrderLineItemLotDataEntryList processStepLotList) 
	{
		PurchaseOrderLineItemLotDataEntry lot = null;
		if ( processStepLotList != null && processStepLotList.size() > 0 )
		{
			for( int i = 0; i < processStepLotList.size(); i++ )
			{
				lot = (PurchaseOrderLineItemLotDataEntry)processStepLotList.get( i );
				System.out.println( lot.isSelected() + "  " + lot.getLotNumber() + "	" + lot.getQtyIn() + "	" + lot.getQtyPulled() );
			}
		}
	}
	
	/**
	 * @param purchaseOrderLineItemLotDataEntryList
	 * @param receivingLineItemList
	 */
	private void removeExistingProcessStepIds(PurchaseOrderLineItemLotDataEntryList purchaseOrderLineItemLotDataEntryList, ReceivingLineItemList receivingLineItemList) 
	{
		Iterator receivingLineItemIterator = null;
		Iterator lotIterator = null;
		ReceivingLineItem recevingLineItem = null;
		PurchaseOrderLineItemLotDataEntry lot = null;
		PurchaseOrderLineItemLotDataEntryList filteredPurchaseOrderList = new PurchaseOrderLineItemLotDataEntryList();
		
		if( receivingLineItemList != null && receivingLineItemList.size() > 0 && purchaseOrderLineItemLotDataEntryList != null && purchaseOrderLineItemLotDataEntryList.size() > 0 )
		{
			receivingLineItemIterator = receivingLineItemList.iterator();
			filteredPurchaseOrderList.addAll( purchaseOrderLineItemLotDataEntryList );
			while( receivingLineItemIterator.hasNext() )
			{
				recevingLineItem = (ReceivingLineItem)receivingLineItemIterator.next();
				lotIterator = filteredPurchaseOrderList.iterator();
				
				while( lotIterator.hasNext() )
				{
					lot = (PurchaseOrderLineItemLotDataEntry)lotIterator.next();
					
					if( recevingLineItem.getProcessStepId() == lot.getProcessStepId() )
					{
						purchaseOrderLineItemLotDataEntryList.remove( lot );
					}
				}
			}
		}
	}
}
